import traceback


class Environment:
    env_set = []
    pause_flag = False

    def __init__(self, parent=None):
        # 存储变量或函数的映射
        self.bindings = {}
        # 父环境，用于支持作用域和原型链
        self.parent = parent
        self.__return_flag = False
        self.prototype = None

    def __enter__(self):
        Environment.env_set.append(self)

    def __exit__(self, exc_type, exc_val, exc_tb):
        Environment.env_set.remove(self)
        if exc_type is not None:
            print(f"An exception occurred: {exc_type}, {exc_val}")
            traceback.print_tb(exc_tb)
            return True  # 吞掉异常

    def return_call(self):
        self.__return_flag = True

    def return_reset(self):
        self.__return_flag = False

    def is_return(self):
        return self.__return_flag

    def define(self, name, value):
        # 定义一个新的绑定
        self.bindings[name] = value

    def update(self, name, value):
        if name in self.bindings:
            self.bindings[name] = value
        elif self.parent:
            return self.parent.update(name, value)
        else:
            raise NameError("Name '{}' not found".format(name))

    def lookup(self, name):
        # 查找一个绑定的值
        if name in self.bindings:
            return self.bindings[name]
        elif self.parent:
            return self.parent.lookup(name)
        else:
            raise NameError("Name '{}' not found".format(name))
